package com.htd.base.common.util;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.htd.base.common.config.LsCoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class DataBaseUtils {

    @Autowired
    private LsCoreProperties lsCoreProperties;

    @Autowired
    private DynamicDataSourceProperties dynamicDataSourceProperties;

    /**
     * 获取自动部署开关
     * @return  自动部署开关
     */
    public Boolean getLangDbAutoDeploymentEnabled() {
        // 多語言功能開啟+自动部署功能開啟
        return lsCoreProperties.getBase().language().getOpen() && lsCoreProperties.getBase().language().database().auto_deployment_enabled();
    }

    /**
     * 获取系统默认数据源类型
     * @return  数据源类型
     */
    public String getLangDbType() {
        return lsCoreProperties.getBase().language().database().getType();
    }

    /**
     * 获取系统默认数据源 key
     * @return 数据源 key
     */
    public String getPrimaryKey() {
        return dynamicDataSourceProperties.getPrimary();
    }

    /**
     * 获取语言表所在数据源 key
     * @return 数据源 key
     */
    public String getLangDbKey() {
        return StringUtils.isNotEmpty(lsCoreProperties.getBase().language().database().getKey())
                ? lsCoreProperties.getBase().language().database().getKey()
                : dynamicDataSourceProperties.getPrimary();
    }

    /**
     * 切换数据源
     */
    public void changeLangDataSource(String databaseKey) {
        try {
            if (!Objects.equals(DynamicDataSourceContextHolder.peek(), databaseKey)) {
                // 动态切换数据源
                DynamicDataSourceContextHolder.push(databaseKey);
                log.info("[Trans. plugin] 自動切換到数据源： {}", databaseKey);
            } else {
                log.info("[Trans. plugin] 已經在数据源： {}", databaseKey);
            }
        } catch (Exception e) {
            log.error("[Trans. plugin] 自動切換到数据源失败", e);
        }
    }
}
